import os

def clear_proto(path):
    if os.path.exists(path):
        os.remove(path)

def wrap_pbts_result(path):
    # 读取原始文件内容
    with open(path, 'r', encoding='utf-8') as file:
        original_content = file.read()

    # 写入新的内容，包含 namespace 和 export default
    with open(path, 'w', encoding='utf-8') as file:
        file.write(f"""declare global {{
namespace proto {{
{original_content}
}}
}}
export default proto;
""")

def wrap_pbjs_result(path):
    # 读取原始文件内容
    with open(path, 'r', encoding='utf-8') as file:
        original_content = file.read()
        original_content = original_content.replace('protobufjs/minimal.js','../3rd/protobuf.js')
        original_content += "(window || global).proto = $root"
        with open(path, 'w', encoding='utf-8') as file:
            file.write(original_content)

def copyTo(src, des):
    clear_proto(des)
    
    # 打开源文件并读取其内容
    with open(src, 'r', encoding='utf-8') as file:
        original_content = file.read()
    
    # 打开目标文件并写入源文件的内容
    with open(des, 'w', encoding='utf-8') as file:
        file.write(original_content)

def main():
    protoJs = 'proto.js'
    protoTs = 'proto.d.ts'
    msg = 'msg.ts'
    asset_path = '../../assets/proto/' 
    server_path = '../../../server/src/proto/'
    clear_proto(os.path.join(asset_path, protoJs))
    print('-----cancel proto.js')
    clear_proto(os.path.join(asset_path, protoTs))
    print('-----cancel proto.Ts')
    os.system('cd ../../')
    os.system('npm run build-proto:pbjs')
    os.system('npm run build-proto:pbts')
    wrap_pbts_result(os.path.join(asset_path, protoTs))
    print('-----wrap proto.d.ts')
    copyTo(os.path.join(asset_path, protoJs), os.path.join(server_path, protoJs))
    copyTo(os.path.join(asset_path, protoTs), os.path.join(server_path, protoTs))
    print('-----copyToServer')
    wrap_pbjs_result(os.path.join(asset_path, protoJs))
    print('-----wrap proto.d.js')
    copyTo(msg, os.path.join(asset_path, msg))
    copyTo(msg, os.path.join(server_path, msg))
    print('-----finish')

if __name__ == "__main__":
    main()